<?php
class LyCacheFile {
	protected $options = array();
	function setOptions($options){
		$this->options = array_merge($this->options,$options);
	}
	function add($key,$value,$ttl){
		if(null == $ttl){
			$ttl = $this->options['ttl'];
		}
		$filename = $this->buildFilename($key);
		$expireTime = (0 == $ttl) ? '0000000000' : (time()+$ttl);
		return (boolean) file_put_contents($filename, '<?php exit;?>' . $expireTime . serialize($value));
	}
	function get($key){
		$filename = $this->buildFilename($key);
		if (!is_file($filename))
		{
			return false;
		}
		else
		{
			// php > 5.1.0
			$ttl = file_get_contents($filename,false,null,13,10);
			if(0 != $ttl && time() > $ttl)
			{
				@unlink($filename);
				return false;
			}
			else
			{
				return unserialize(file_get_contents($filename,false,null,23));
			}
		}
	}
	function del($key){
		$filename = $this->buildFilename($key);
		if(is_file($filename)){
			@unlink($filename);
		}
		return;
	}
	function buildFilename($key){
		$token = md5(trim($key));
		$path = rtrim($this->options['cacheDir'],'/\\ ').DIRECTORY_SEPARATOR.'__file__cache__'.DIRECTORY_SEPARATOR.substr($token,0,2).DIRECTORY_SEPARATOR.substr($token,2,2);
		if(!is_dir($path)){
			@mkdir($path,0777,true);
		}
		return $path.DIRECTORY_SEPARATOR.'cache-'.$token.'.php';
	}

}